﻿@page "/home/home"
@using Microsoft.JSInterop;
@using Newtonsoft.Json;
@using TMV.Application.AbnormalRecords.Services;
@using TMV.Application.Tr.Services;
@using TMV.Application.Scale.Services;
@using TMV.Application.TransportPlan.Services;
@using TMV.Application.Car.Services;
@using TMV.DTO.AbnormalRecords;
@using TMV.DTO.Tr;
@using TMV.Web.Pages.AbnormalRecords.ViewModel;
@using TMV.Web.Pages.TransportationRecords.ViewModel;
@using Microsoft.AspNetCore.SignalR.Client
@using StackExchange.Profiling.Internal;
@inject NavigationManager Navigation
@implements IAsyncDisposable
@inherits ProCompontentBase
@inject IScaleServiceDM _scale
@inject ITrServiceDM _tr
@inject ITransportPlanServiceDM _tran
@inject ICarServiceDM _car
@inject IJSRuntime Js;
@attribute [Authorize]


<MRow Style="height: 100%;margin-top:4px;">
    <MCol Md=8 Sm=12 Class="max-height" Style="padding-bottom:0;">
        <MRow Style="height: 160px">
            <MCol Md=12 Sm=12 Class="max-height" Style="padding-top:0;">
                <div style="padding:10px;display:flex;justify-content:flex-start;">
                    <MCard Class="max-height" Style="padding:0 32px 8px 32px;margin-right:32px;height:144px!important;">
                        <MCardTitle Style="padding:4px 0;"><MIcon Small Left>mdi-scale-balance</MIcon><span style="font-size:16px;">衡器</span></MCardTitle>
                        <MRadioGroup @bind-Value="Heng" Column Style="margin-top:0;" Disabled="@all.status.Equals("0")" Filled="@all.status.Equals("0")">
                            @foreach (var item in _scleList)
                            {
                                <MRadio Label="@item.Name"
                                    Color="primary"
                                    Value="item.Type">
                                </MRadio>
                            }
                        </MRadioGroup>
                    </MCard>
                    <MCard Class="max-height" Style="padding:0 32px 8px 32px;margin-right:32px;">
                        <MCardTitle Style="padding:4px 0;"><MIcon Small Left>mdi-weight-pound</MIcon><span style="font-size:16px;">称重</span></MCardTitle>
                        <div style="display:flex;width:200px;justify-content:flex-end;flex-wrap:wrap;">
                            <div style="background-color:yellow;height:64px;line-height:64px;text-align:right;font-size:48px;width:200px;font-weight:bolder;padding:0 24px;">@authorizationDTO.Weight</div>
                            <div class="@Active()" style="width:24px;height:24px;border-radius:24px;margin-top:8px;margin-right:8px;"></div><div style="height:24px;line-height:24px;margin-top:8px;">稳定</div>
                        </div>
                    </MCard>
                    <MCard Class="max-height" Style="padding:0 32px 8px 32px;margin-right:16px;">
                        <MCardTitle Style="padding:4px 0;"><MIcon Small Left>mdi-line-scan</MIcon><span style="font-size:16px;">红外线</span></MCardTitle>
                        <div style="display:flex;">
                            <div style="width:24px;height:96px;background-color:red;"></div>
                            <div style="height:96px;padding:0 24px;">
                                <div style="display:flex;justify-content:space-between;">
                                    <div class="@Active1()" style="width:16px;height:16px;border-radius:16px;margin-bottom:8px;"></div>
                                    <div class="@Active2()" style="width:16px;height:16px;border-radius:16px;margin-bottom:8px;"></div>
                                </div>
                                <div style="width:200px;background-color:#aaa;height:48px;"></div>
                                <div style="display:flex;justify-content:space-between;">
                                    <div class="@Active1()" style="width:16px;height:16px;border-radius:16px;margin-top:8px;"></div>
                                    <div class="@Active2()" style="width:16px;height:16px;border-radius:16px;margin-top:8px;"></div>
                                </div>
                            </div>
                            <div style="width:24px;height:96px;background-color:red;"></div>
                        </div>
                    </MCard>
                </div>
            </MCol>
        </MRow>
        <MRow Style="height: calc(100% - 160px)">
            <MCol Md=12 Sm=12 Class="max-height" Style="padding-bottom:0;">
                <MCard Class="max-height">
                    <MContainer Fluid>
                        <MRow Align="@AlignTypes.Center">
                            <MCol Cols="4">
                                <MTextField @bind-Value="all.dh" Label="矿号" Filled="@all.status.Equals("0")" Outlined Clearable Disabled="@all.status.Equals("0")"></MTextField>
                            </MCol>
                            <MCol Cols="8">
                                <MSelect Items="_items_state" @bind-Value="all.status" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Label="工作状态" Outlined></MSelect>
                            </MCol>
                            <MCol Cols="4">
                                <MSelect Items="_items_car" @bind-Value="all.car" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Filled="@all.status.Equals("0")" Label="车号" Outlined Disabled="@all.status.Equals("0")"></MSelect>
                            </MCol>
                            <MCol Cols="4">
                                <MSelect Items="_items_driver" @bind-Value="all.driver" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Filled="@all.status.Equals("0")" Label="驾驶员" Outlined Disabled="@all.status.Equals("0")"></MSelect>
                            </MCol>
                            <MCol Cols="4">
                                <MTextField @bind-Value="all.mz" Label="毛重" Filled="@all.status.Equals("0")" Outlined Suffix="吨" Clearable Disabled="@all.status.Equals("0")"> </MTextField>
                            </MCol>
                            <MCol Cols="8">
                                <MSelect Items="_items_send" @bind-Value="all.send" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Filled="@all.status.Equals("0")" Label="发货单位" Outlined Disabled="@all.status.Equals("0")"></MSelect>
                            </MCol>
                            <MCol Cols="4">
                                <MTextField @bind-Value="all.pz" Label="皮重" Filled="@all.status.Equals("0")" Outlined Suffix="吨" Clearable Disabled="@all.status.Equals("0")"> </MTextField>
                            </MCol>
                            <MCol Cols="8">
                                <MSelect Items="_items_recive" @bind-Value="all.recive" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Filled="@all.status.Equals("0")" Label="收货单位" Outlined Disabled="@all.status.Equals("0")"></MSelect>
                            </MCol>
                            <MCol Cols="4">
                                <MTextField @bind-Value="all.kz" Label="扣重" Filled="@all.status.Equals("0")" Outlined Suffix="吨" Clearable Disabled="@all.status.Equals("0")"> </MTextField>
                            </MCol>
                            <MCol Cols="4">
                                <MSelect Items="_items_names" @bind-Value="all.names" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Filled="@all.status.Equals("0")" Label="货物名称" Outlined Disabled="@all.status.Equals("0")"></MSelect>
                            </MCol>
                            <MCol Cols="4">
                                <MSelect Items="_items_meta" @bind-Value="all.meta" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Filled="@all.status.Equals("0")" Label="规格型号" Outlined Disabled="@all.status.Equals("0")"></MSelect>
                            </MCol>
                            <MCol Cols="4">
                                <MTextField @bind-Value="all.jz" Label="净重" Filled="@all.status.Equals("0")" Outlined Suffix="吨" Clearable Disabled="@all.status.Equals("0")"> </MTextField>
                            </MCol>
                            <MCol Cols="4">
                                <MSelect Items="_items_tran" @bind-Value="all.tran" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Filled="@all.status.Equals("0")" Label="承运单位" Outlined Disabled="@all.status.Equals("0")"></MSelect>
                            </MCol>
                            <MCol Cols="4">
                                <MSelect Items="_items_ticket" @bind-Value="all.ticket" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Filled="@all.status.Equals("0")" Label="货单号" Outlined Disabled="@all.status.Equals("0")"></MSelect>
                            </MCol>
                            <MCol Cols="4">
                                <MTextField @bind-Value="all.dj" Label="单价" Filled="@all.status.Equals("0")" Outlined Suffix="元/吨" Clearable Disabled="@all.status.Equals("0")"> </MTextField>
                            </MCol>
                            <MCol Cols="4">
                                <MSelect Items="_items_boat" @bind-Value="all.boat" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Filled="@all.status.Equals("0")" Label="船名" Outlined Disabled="@all.status.Equals("0")"></MSelect>
                            </MCol>
                            <MCol Cols="4">
                                <MSelect Items="_items_down" @bind-Value="all.down" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Filled="@all.status.Equals("0")" Label="卸煤点" Outlined Disabled="@all.status.Equals("0")"></MSelect>
                            </MCol>
                            <MCol Cols="4">
                                <MTextField @bind-Value="all.je" Label="金额" Filled="@all.status.Equals("0")" Outlined Suffix="元" Clearable Disabled="@all.status.Equals("0")"> </MTextField>
                            </MCol>
                            <MCol Cols="4">
                                <MSelect Items="_items_outin" @bind-Value="all.outin" ItemText="u => u.Label"
                                         ItemValue="u => u.Value" Filled="@all.status.Equals("0")" Label="进出" Outlined Disabled="@all.status.Equals("0")"></MSelect>
                            </MCol>
                            <MCol Cols="8">
                                <MTextarea AutoGrow Label="备注" Rows="2" Outlined Shaped Filled="@all.status.Equals("0")" Disabled="@all.status.Equals("0")"></MTextarea>
                            </MCol>
                        </MRow>
                        <MRow Style="margin-top:64px;">
                            <MCol Align="AlignTypes.Center" Cols="3" Style="padding:0;text-align:center;">
                                <MButton class="ma-2" Color="info" Disabled="@all.status.Equals("0")" OnClick="e=>AddTransportationRecords()">
                                    <LoaderContent>
                                        <span class="custom-loader"><MIcon>mdi-cached</MIcon></span>
                                    </LoaderContent>
                                    <ChildContent>
                                        存重
                                    </ChildContent>
                                </MButton>
                            </MCol>
                            <MCol Align="AlignTypes.Center" Cols="3" Style="padding:0;text-align:center;">
                                <MButton class="ma-2" Color="info" Disabled="@all.status.Equals("0")" OnClick="e=>UpTransportationRecords()">
                                    <LoaderContent>
                                        <span class="custom-loader"><MIcon>mdi-cached</MIcon></span>
                                    </LoaderContent>
                                    <ChildContent>
                                        存盘
                                    </ChildContent>
                                </MButton>
                            </MCol>
                            <MCol Align="AlignTypes.Center" Cols="3" Style="padding:0;text-align:center;">
                                <MButton class="ma-2" Color="info" Disabled="@all.status.Equals("0")">
                                    <LoaderContent>
                                        <span class="custom-loader"><MIcon>mdi-cached</MIcon></span>
                                    </LoaderContent>
                                    <ChildContent>
                                        预览
                                    </ChildContent>
                                </MButton>
                            </MCol>
                            <MCol Align="AlignTypes.Center" Cols="3" Style="padding:0;text-align:center;">
                                <MButton class="ma-2" Color="info" Disabled="@all.status.Equals("0")" OnClick="e=>Print()">
                                    <LoaderContent>
                                        <span class="custom-loader"><MIcon>mdi-cached</MIcon></span>
                                    </LoaderContent>
                                    <ChildContent>
                                        打印
                                    </ChildContent>
                                </MButton>
                            </MCol>
                        </MRow>
                    </MContainer>
                </MCard>
            </MCol>
        </MRow>
    </MCol>
    <MCol Md=4 Sm=12 Class="max-height">
        <MCard Class="max-height" style="padding:16px;">
            @if (Heng == 1)
            {
                <img id="img11" style="height:50%;width:100%;background-color:rgba(0,0,0,.2);" />
                <img id="img12" style="height:50%;width:100%;background-color:rgba(0,0,0,.2);" />
            }
            else if (Heng == 2)
            {
                <img id="img21" style="height:50%;width:100%;background-color:rgba(0,0,0,.2);" />
                <img id="img22" style="height:50%;width:100%;background-color:rgba(0,0,0,.2);" />
            }
            else if (Heng == 2)
            {
                <img id="img31" style="height:50%;width:100%;background-color:rgba(0,0,0,.5);" />
                <img id="img32" style="height:50%;width:100%;background-color:rgba(0,0,0,.5);" />
            }
        </MCard>
    </MCol>
</MRow>


@code {
    public HubConnection? hubConnection;

    public bool isAuto { get; set; } = true;

    public int Heng = 1;//衡 默认1号
    public List<DTO.Scale.ScaleDTO> _scleList = new List<DTO.Scale.ScaleDTO>();//衡列表
    public List<DTO.TransportPlan.TransportPlanDTO> _plans = new();//进煤计划
    public List<DTO.Car.CarDTO> _cars = new();//车辆信息
    public AuthorizationDTO authorizationDTO = new();//衡状态

    public class All
    {
        public string status { get; set; }//运行状态
        public string dh { get; set; }//单号
        public decimal mz { get; set; }
        public decimal pz { get; set; }
        public decimal kz { get; set; }
        public decimal jz { get; set; }
        public decimal dj { get; set; }
        public decimal je { get; set; }
        public string car { get; set; }//车号
        public string driver { get; set; }//司机
        public string send { get; set; }//发红单位
        public string recive { get; set; }//收获单位
        public string meta { get; set; }//规格类型
        public string tran { get; set; }//承运单位
        public string ticket { get; set; }//货单号
        public string boat { get; set; }//船名
        public string down { get; set; }//卸煤点
        public string outin { get; set; }//进出
        public string names { get; set; }//货物名称
    }

    All all = new()
        {
            status = "0",
            outin = "0",
            dh = "",
            mz = 0,
            pz = 0,
            kz = 0,
            jz = 0,
            dj = 0,
            je = 0,
            names = "0",
            down = "0"

        };

    public class Item
    {
        public string Label { get; set; }
        public string Value { get; set; }
        public Item(string label, string value)
        {
            Label = label;
            Value = value;
        }
    }

    public string Active()
    {
        return authorizationDTO.State == 0 ? "mmm-active" : "mmm-lock";
    }

    public string Active1()
    {
        return authorizationDTO.inX == 1 ? "mmm-active" : "mmm-lock";
    }

    public string Active2()
    {
        return authorizationDTO.outX == 1 ? "mmm-active" : "mmm-lock";
    }

    /// <summary>
    /// 状态
    /// </summary>
    List<Item> _items_state = new()
        {
            new Item("无人值守", "0"),
            new Item("人工接管", "1"),
        };
    /// <summary>
    /// 进出
    /// </summary>
    List<Item> _items_outin = new()
        {
            new Item("进厂", "0"),
            new Item("出厂", "1"),
            new Item("内转", "2"),
        };
    /// <summary>
    /// 货物名
    /// </summary>
    List<Item> _items_names = new()
        {
            new Item("烟煤", "0"),
        };
    /// <summary>
    /// 车号
    /// </summary>
    List<Item> _items_car = new();
    /// <summary>
    /// 司机
    /// </summary>
    List<Item> _items_driver = new();
    /// <summary>
    /// 发货单位
    /// </summary>
    List<Item> _items_send = new();
    /// <summary>
    /// 司收货单位
    /// </summary>
    List<Item> _items_recive = new();
    /// <summary>
    /// 规格型号
    /// </summary>
    List<Item> _items_meta = new();
    /// <summary>
    /// 承运单位
    /// </summary>
    List<Item> _items_tran = new();
    /// <summary>
    /// 货单号
    /// </summary>
    List<Item> _items_ticket = new();
    /// <summary>
    /// 船名
    /// </summary>
    List<Item> _items_boat = new();
    /// <summary>
    /// 卸煤点
    /// </summary>
    List<Item> _items_down = new()
        {
            new Item("煤场", "0"),
            new Item("卸煤沟", "1"),
        };

    protected override async Task OnInitializedAsync()
    {
        hubConnection = new HubConnectionBuilder()
            .WithUrl(Navigation.ToAbsoluteUri("/chathub"))
            .Build();

        hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
        {
            if (all.status.Equals("0"))
            {
                //反序列化并赋值
                if (user == "HengZ" || user == "HengQ")
                {
                    authorizationDTO = message.FromJson<AuthorizationDTO>();
                    if (authorizationDTO != null)
                    {
                        //当前衡
                        Heng = authorizationDTO.ClassName;
                        if (user == "HengZ")
                        {
                            all.mz = authorizationDTO.Weight;
                            all.pz = 0;
                        }
                        else
                        {
                            all.pz = 0;
                            all.pz = authorizationDTO.Weight;
                        }
                        var car = _cars.FirstOrDefault(x => x.PlateNumber == authorizationDTO.PlateNumber);
                        if (car != null)
                        {
                            all.car = car.PlateNumber;
                            all.driver = car.DriverName;
                        }
                        var plan = _plans.FirstOrDefault(x => x.MineCode == authorizationDTO.CollieryCode);
                        if (plan != null)
                        {
                            all.dh = plan.MineCode;
                            all.boat = plan.ShipName;
                            all.send = plan.SendUnit;
                            all.recive = plan.ReceiptUnit;
                            all.tran = plan.Carrier;
                            all.ticket = plan.Code;
                        }
                        InvokeAsync(StateHasChanged);
                    }
                }
            }
        });

        await hubConnection.StartAsync();
    }

    public bool IsConnected =>
        hubConnection?.State == HubConnectionState.Connected;

    public async ValueTask DisposeAsync()
    {
        if (hubConnection is not null)
        {
            await hubConnection.DisposeAsync();
        }
    }
    protected override void OnInitialized()
    {
        Initialize();

    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await Js.InvokeVoidAsync("onPlay", Heng);
        }
        base.OnAfterRender(firstRender);
    }
    public void Initialize()
    {
        var dto = new Request_ScalageRecordsDTO2();
        _scleList = _scale.GetScaleList(new DTO.Scale.Request_Scale()).Data;
        DTO.TransportPlan.Request_TransportPlan tran = new DTO.TransportPlan.Request_TransportPlan() { PageSize = 1000 };
        _plans = _tran.GetTransportPlanList(tran).Data;
        if (_plans != null)
        {
            _plans.ForEach(item =>
            {
                _items_send.Add(new Item(item.SendUnit, item.SendUnit));
                _items_recive.Add(new Item(item.ReceiptUnit, item.ReceiptUnit));
                _items_tran.Add(new Item(item.Carrier, item.Carrier));
                _items_boat.Add(new Item(item.ShipName, item.ShipName));
                _items_ticket.Add(new Item(item.Code, item.Code));
            });
        }
        DTO.Car.Request_Car car = new DTO.Car.Request_Car() { PageSize = 1000 };
        _cars = _car.GetCarList(car).Data;
        if (_cars != null)
        {
            _cars.ForEach(item =>
            {
                _items_car.Add(new Item(item.PlateNumber, item.PlateNumber));
                _items_driver.Add(new Item(item.DriverName, item.DriverName));
            });
        }
        /**
     * 衡编码
     * 1入 39cffe095e31455eabcc86ba0d8ba5f2
     * 1出 941be0a7156344c5b5f2c2085806669c
     * 2入 1620017d65b94409b4dadbfb99d0ee1a
     * 2出 1620017d65b94409b4dadbfb99d0ee1a
     * 3入 bf6e2f7da0384c2090779f6a5efa324b
     * 3出 21ddf92963e3496ca290d8d754fd95bb
     * */
        //GetRtsps("39cffe095e31455eabcc86ba0d8ba5f2");
    }



    public string GetRtsps(string code)
    {
        HttpUtil.SetPlatformInfo("21178776", "J9t8TVARJ2fah1jrAmVT", "192.168.1.5", 443, true);

        string body = JsonConvert.SerializeObject(new
        {
            cameraIndexCode = code,
            streamType = 0,
            protocol = "rtsp",
            transmode = 1,
            expand = "transcode=0",
            streamform = "rtp"
        });

        // 填充Url
        string uri = "/api/video/v2/cameras/previewURLs";

        // 发起POST请求，超时时间15秒，返回响应字节数组
        byte[] result = HttpUtil.HttpPost(uri, body, 15);
        if (null == result)
        {
            // 请求失败
            Console.WriteLine("/api/video/v2/cameras/previewURLs: POST fail");
            return null;
        }
        else
        {
            string strModel = System.Text.Encoding.UTF8.GetString(result);
            RtspModel rtspModel = strModel != null ? JsonConvert.DeserializeObject<RtspModel>(strModel) : new RtspModel();
            return rtspModel?.data.url;
        }
    }

    public void HengChange() => Console.WriteLine("Heng:", Heng);

    /// <summary>
    /// 打印
    /// </summary>
    public void Print()
    {
        try
        {
            if (all.car.IsNullOrWhiteSpace() || all.ticket.IsNullOrWhiteSpace())
            {
                PopupService.ToastAsync("车号/货单号不能为空", AlertTypes.Error);
                return;
            }
            //获取打印数据
            var print = _tr.GetPrint(new AuthorizationDTO() { PlateNumber = all.car, CollieryCode = all.ticket });
            if (print == null)
            {
                PopupService.ToastAsync("该票据还不能打印", AlertTypes.Error);
                return;
            }
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect("127.0.0.1", 5888);
            string data = JsonConvert.SerializeObject(print);
            Byte[] bytesSent = Encoding.UTF8.GetBytes(data);
            socket.Send(bytesSent, bytesSent.Length, 0);
        }
        catch (Exception ex)
        {
            Log.Error("链接失败:" + ex.Message);
        }
    }

    /// <summary>
    /// 存重
    /// </summary>
    public void AddTransportationRecords()
    {
        var r = _tr.AddTransportationRecords(new TransportationRecordsModel()
            {
                PlateNumber = all.car,
                Weight = all.mz,
                MineCode = all.ticket,
                ScaleName = Heng.ToString()
            });
        if (r.IsSuccess)
        {
            PopupService.ToastAsync("存重成功", AlertTypes.Success);
        }
        else
        {
            PopupService.ToastAsync("存重成功", AlertTypes.Error);
        }
    }

    /// <summary>
    /// 存盘
    /// </summary>
    public void UpTransportationRecords()
    {
        var r = _tr.UpTransportationRecords(new TransportationRecordsModel()
            {
                PlateNumber = all.car,
                Weight = all.pz,
                MineCode = all.ticket,
                ScaleName = Heng.ToString()
            });
        if (r.IsSuccess)
        {
            PopupService.ToastAsync("存盘成功", AlertTypes.Success);
        }
        else
        {
            PopupService.ToastAsync("存盘成功", AlertTypes.Error);
        }
    }

    class RtspModel
    {
        public string code { get; set; }
        public string msg { get; set; }
        public RtspUrl data { get; set; }
    }

    class RtspUrl
    {
        public string url { get; set; }
    }
}
